<template>
  <div>
    <el-dialog v-drag width="94%" height="100%" :fullscreen="false" v-drag
      :title="!dataForm.acceptId ? '新增采购验收' : '修改采购验收'" :close-on-click-modal="false" :visible.sync="visible">
      <el-form :model="dataForm" :inline="true" :rules="dataRule" ref="dataForm" @keyup.enter.native="dataFormSubmit()"
        label-width="80px">
        <el-form-item label="验收编号" prop="acceptNo">
          <el-input size="mini" v-model="dataForm.acceptNo" disabled placeholder="验收编号" style="width:100%;"  clearable></el-input>
        </el-form-item>
        <el-form-item label="验收日期" prop="acceptDate">
          <el-date-picker size="mini" style="width:100%;" v-model="dataForm.acceptDate" value-format="yyyy-MM-dd"
            type="date" clearable placeholder="验收日期">
          </el-date-picker>
        </el-form-item>
        <el-form-item label="供应商" prop="supplierName">
          <el-select size="mini" @focus="getSuppliers()" @change="setSuppliers()" v-model="dataForm.supplierName"
            clearable placeholder="请选择" style="width:100%;" >
            <el-option v-for="item in suppliers" :key="item.supplierId" :label="item.supplierName"
              :value="item.supplierName">
            </el-option>
          </el-select>
        </el-form-item>
        <el-form-item label="总金额" prop="totalAmount">
          <el-input size="mini" v-model="dataForm.totalAmount" disabled placeholder="总金额" style="width:100%;" ></el-input>
        </el-form-item>
        <el-form-item label="制单人" prop="makeUsername">
          <el-select size="mini" @focus="getUsers()" @change="setUsers()" v-model="dataForm.makeUsername" clearable
            placeholder="请选择">
            <el-option v-for="item in users" :key="item.userId" :label="item.username" :value="item.username">
            </el-option>
          </el-select>
        </el-form-item>
        <el-form-item label="验收人" prop="acceptUsername">
          <el-select size="mini" @focus="getUsers()" @change="setUsers()" v-model="dataForm.acceptUsername" clearable
            placeholder="请选择">
            <el-option v-for="item in users" :key="item.userId" :label="item.username" :value="item.username">
            </el-option>
          </el-select>
          <!-- <el-input v-model="dataForm.purchaseUserId"></el-input> -->
        </el-form-item>
        <el-form-item label="审批人" prop="auditUsername">
          <el-select size="mini" @focus="getUsers()" @change="setUsers()" v-model="dataForm.auditUsername" clearable
            placeholder="请选择">
            <el-option v-for="item in users" :key="item.userId" :label="item.username" :value="item.username">
            </el-option>
          </el-select>
        </el-form-item>
        <el-form-item label="总部单号" prop="headquarterNo">
          <el-input size="mini" type="input"  v-model="dataForm.headquarterNo" placeholder="总部单号" clearable></el-input>
        </el-form-item>
        <el-form-item label="备注" prop="remark">
          <el-input size="mini" type="textarea" :autosize="{ minRows: 1, maxRows: 4}" v-model="dataForm.remark"
            placeholder="备注" clearable></el-input>
        </el-form-item>
      </el-form>

      <!-- 子表 -->
      <el-divider></el-divider>
      <el-form>
        <el-form-item>
          <el-button class="line-button" size="mini" circle type="primary" @click="addRow()"><span
              class="icon iconfont">&#xe664;</span></el-button>
          <el-button class="line-button" size="mini" circle type="danger" @click="deleteRows()"><span
              class="icon iconfont">&#xe813;</span></el-button>
        </el-form-item>
      </el-form>
      <el-table :data="itemDataList" border size="mini" class="item-table" height="250"
        @selection-change="selectionChangeHandle" ref="itemTable"
        :header-cell-style="{ background: '#fcfcfc', color: '#606266', height:'36px'}">
        <el-table-column type="selection" header-align="center" align="center" width="50">
        </el-table-column>
        <el-table-column type="index" header-align="center" align="center" width="40" label="#">
        </el-table-column>
        <el-table-column prop="goodsCode" header-align="center" width="150" align="center" label="药品编码">
          <template slot-scope="scope">
            <div class="goods-code-box" v-if="scope.row.goodsCode == ''">
              <el-input size="mini" v-model="scope.row.goodsCode" :disabled="true" class="goods-code-input"
                @blur='blurInput(scope.row, "goodsCode", scope.row.goodsCode)'> </el-input>
              <el-button size="mini" class="chose-button" @click="selectGoods(scope.row)"><span
                  class="icon iconfont">&#xe68e;</span></el-button>
            </div>
            <span v-else>{{scope.row.goodsCode}}</span>
          </template>
        </el-table-column>
        <el-table-column prop="goodsName" header-align="center" width="180" align="center" label="药品名称">
        </el-table-column>
        <el-table-column prop="barCode" header-align="center" width="100" align="center" label="条码">
        </el-table-column>
        <el-table-column prop="stockNum" header-align="center" width="130" align="center" label="当前库存数量">
        </el-table-column>
        <el-table-column prop="purchaseNum" header-align="center" width="130" align="center" label="采购数量">
          <template slot-scope="scope">
            <el-input size="mini" v-model="scope.row.purchaseNum"
              @blur='blurInput(scope.row, "purchaseNum", scope.row.purchaseNum)' v-focus> </el-input>
          </template>
        </el-table-column>
        <el-table-column prop="lastInPrice" header-align="center" width="100" align="center" label="上次进价">
        </el-table-column>
        <el-table-column prop="purchasePrice" header-align="center" width="130" align="center" label="采购价">
          <template slot-scope="scope">
            <el-input size="mini" v-model="scope.row.purchasePrice"
              @blur='blurInput(scope.row, "purchasePrice", scope.row.purchasePrice)'>
            </el-input>
          </template>
        </el-table-column>
        <el-table-column prop="batchNo" header-align="center" width="100" align="center" label="批号">
          <template slot-scope="scope">
            <el-input size="mini" v-model="scope.row.batchNo"
              @blur='blurInput(scope.row, "batchNo", scope.row.batchNo)' >
            </el-input>
          </template>
        </el-table-column>
        <el-table-column prop="produceDate" header-align="center" width="140" align="center" label="生产日期">
          <template slot-scope="scope">
            <el-date-picker size="mini" type="date" v-model="scope.row.produceDate" value-format="yyyy-MM-dd" placeholder="选择日期"
              @blur='blurInput(scope.row, "produceDate", scope.row.produceDate)' >
            </el-date-picker>
          </template>
        </el-table-column>
        <el-table-column prop="expiredDate" header-align="center" width="140" align="center" label="有效期">
          <template slot-scope="scope">
            <el-date-picker size="mini" type="date" v-model="scope.row.expiredDate" value-format="yyyy-MM-dd" placeholder="选择日期"
              @blur='blurInput(scope.row, "expiredDate", scope.row.expiredDate)' >
            </el-date-picker>
          </template>
        </el-table-column>
        <el-table-column prop="genericName" header-align="center" width="180" align="center" label="通用名称">
        </el-table-column>
        <el-table-column prop="standard" header-align="center" width="140" align="center" label="规格">
        </el-table-column>
        <el-table-column prop="unit" header-align="center" align="center" label="单位">
        </el-table-column>
        <el-table-column prop="producingArea" header-align="center" width="180" align="center" label="产地">
        </el-table-column>
        <el-table-column prop="produceFactory" header-align="center" width="180" align="center" label="生产单位">
        </el-table-column>
        <el-table-column prop="approvalNo" header-align="center" width="140" align="center" label="批准文号">
        </el-table-column>
        <el-table-column prop="dosageForm" header-align="center" width="160" align="center" label="剂型">
        </el-table-column>
        <el-table-column prop="remark" header-align="center" width="150" align="center" label="备注">
          <template slot-scope="scope">
            <el-input size="mini" v-model="scope.row.remark" type="textarea"
              @blur='blurInput(scope.row, "remark", scope.row.remark)' autosize>
            </el-input>
          </template>
        </el-table-column>
        <el-table-column fixed="right" align="center" label="操作" width="100">
          <template slot-scope="scope">
            <el-button size="mini" type="danger" icon="el-icon-minus" class="delete-button"
              @click.native.prevent="deleteRow(scope.$index)"></el-button>
          </template>
        </el-table-column>
      </el-table>
      <span slot="footer" class="dialog-footer">
        <el-button size="mini" @click="visible = false">取消</el-button>
        <el-button size="mini" type="primary" @click="dataFormSubmit()">保存</el-button>
      </span>
    </el-dialog>
    <!-- 弹窗, 新增 / 修改 -->
    <goods-select v-if="goodsSelectVisible" ref="goodsSelectRef" @refreshDataList=""></goods-select>
  </div>
</template>

<script>
  import cloneDeep from 'lodash/cloneDeep'
  import GoodsSelect from '@/views/components/product-select.vue'
  export default {
    data() {
      return {
        visible: false,
        goodsSelectVisible: false,
        dataForm: {
          acceptId: undefined,
          acceptNo: '',
          acceptDate: '',
          transportTool: '',
          transportDepartment: '',
          shipmentTime: '',
          arrivalTime: '',
          shipmentPlace: '',
          supplierId: '',
          supplierName: '',
          totalAmount: 0,
          goodsPeerStatus: 1,
          goodsPeerDesc: '',
          transportToolStatus: 1,
          transportToolDesc: '',
          arrivalGoodsStatus: 1,
          arrivalGoodsDesc: '',
          makeUserId: '',
          makeUsername: '',
          acceptUserId: '',
          acceptUsername: '',
          aduidtStatus: 0 ,
          auditUsername: '',
          auditUserId: '',
          remark: '',
          headquarterNo: '',
          itemList:[]
        },
        paymentMethods: [],
        dataRule: {
          acceptNo: [{
            required: true,
            message: '验收编号不能为空',
            trigger: 'blur'
          }],
          orderDate: [{
            required: true,
            message: '验收日期不能为空',
            trigger: 'blur'
          }],
          orderTitle: [{
            required: true,
            message: '验收标题不能为空',
            trigger: 'blur'
          }],
          supplierName: [{
            required: true,
            message: '供应商名称不能为空',
            trigger: 'blur'
          }],
          totalAmount: [{
            required: true,
            message: '总金额不能为空',
            trigger: 'blur'
          }],
          makeUsername: [{
            required: true,
            message: '制单人不能为空',
            trigger: 'blur'
          }],
          auditUsername: [{
            required: true,
            message: '审批人不能为空',
            trigger: 'blur'
          }],
          remark: [{
            required: true,
            message: '备注不能为空',
            trigger: 'blur'
          }]
        },
        itemDataList: [],
        oldData: {},
        showInput: "",
        dataListSelections: [],
        currentGoods: {},
        suppliers: [],
        users: [],
      }
    },
    watch: {
      currentGoods: {
        handler(newVal, oldVal) {
          let order = cloneDeep(newVal)
          order.rowNum = new Date().getTime()
          // order.stockNum = order.stockTotalNum
          // order.lastInPrice = order.inPrice
          order.remark = '';
          let isAdd = false;
          this.itemDataList.forEach((item, index) => {
            if (item.goodsCode === order.goodsCode) {
              isAdd = true;
              this.$message.error("[" + item.goodsCode + "]该药品已经添加！")
              return;
            }
            if (!item.goodsCode) {
              this.itemDataList.splice(index, 1)
            }
          })
          if (!isAdd) {
            this.itemDataList.push(order)
          }
          this.addRow()
        },
        immediate: true
      }
    },
    components: {
      GoodsSelect
    },
    methods: {
      initItemData() {
        if (!this.dataForm.acceptId || this.itemDataList.length === 0) {
          this.itemDataList = []
          this.addRow()
        }
      },
      init(acceptId) {
        console.log("acceptId==", acceptId)
        this.itemDataList = []
        this.dataForm.acceptId = acceptId
        this.visible = true
        this.$nextTick(async () => {
          this.$refs['dataForm'].resetFields()
          if (this.dataForm.acceptId) {
            const res = await this.$http({
              url: `/purchase/purchaseaccept/info/${this.dataForm.acceptId}`,
              method: 'get',
              params: this.$http.adornParams()
            })
            let data = res.data
            console.log("data==", data)
            if (data && data.code === 0) {
              this.dataForm = data.purchaseAccept
              // this.dataForm.status = this.dataForm.status === 1 ? true: false
              data.purchaseAccept.itemList.forEach((item, index) => {
                // item.status = item.status === 1 ? true: false;
                this.itemDataList.push(item)
              })
            }
          } else {
            const res = await this.$http({
              url: `/purchase/purchaseaccept/getAcceptNo`,
              method: 'get',
              params: this.$http.adornParams()
            })
            let data = res.data
            if (data && data.code === 0) {
              this.dataForm.acceptNo = data.data
            }
          }
          this.initItemData()
        })
      },
      // 表单提交
      dataFormSubmit() {
        this.$refs['dataForm'].validate(async (valid) => {
          if (valid) {
            this.itemDataList.forEach((item, index) => {
              item.status = 1
            })
            this.dataForm.itemList = this.itemDataList;
            console.log("this.dataForm===", this.dataForm)
            const res = await this.$http({
              url: `/purchase/purchaseaccept/${!this.dataForm.acceptId ? 'saveOrder' : 'updateOrder'}`,
              method: 'post',
              data: this.$http.adornData(this.dataForm)
            })
            let data = res.data
            if (data && data.code === 0) {
              this.$message({
                message: '操作成功',
                type: 'success',
                duration: 1500,
                onClose: () => {
                  this.visible = false
                  this.$emit('refreshDataList')
                }
              })
            } else {
              this.$message.error(data.msg)
            }
          }
        })
      },
      blurInput(row, name, value) {
        // 判断数据是否有所改变，如果数据有改变则调用修改接口
        if (this.oldData[name] != value) {
          row[name] = value
          //this.saveHandle(row, `/purchase/purchaseacceptitem/update`)
        }
        let totalAmount = 0;
        if(this.itemDataList && this.itemDataList.length > 0){
          this.itemDataList.forEach((item, index) => {
            if (item.purchaseNum && item.purchasePrice) {
              totalAmount += item.purchaseNum * item.purchasePrice
            }
          })
        }
        this.dataForm.totalAmount = totalAmount
        this.showInput = ""
      },
      addRow() {
        let item = {
          rowNum: new Date().getTime(),
          itemId: undefined,
          acceptId: '',
          acceptNo: '',
          goodsId: '',
          goodsCode: '',
          goodsName: '',
          genericName: '',
          standard: '',
          unit: '',
          producingArea: '',
          produceFactory: '',
          approvalNo: '',
          dosageForm: '',
          batchNo: '',
          produceDate: '',
          expiredDate: '',
          barCode: '',
          purchaseNum: 0,
          purchasePrice: 0,
          purchaseAmount: 0,
          lastInPrice: 0,
          oldRetailPrice: 0,
          retailPrice: 0,
          oldMemberPrice: 0,
          memberPrice: 0,
          wholeNum: 0,
          spreadNum: 0,
          remark: ''
        }
        this.itemDataList.push(item)
      },
      deleteRows() {
        this.dataListSelections.forEach((val, index) => {
          this.itemDataList.forEach((v, i) => {
            if (val.rowNum === v.rowNum) {
              // i 为选中的索引
              this.itemDataList.splice(i, 1)
            }
          })
        })
        // 删除完数据之后清除勾选框
        this.$refs.itemTable.clearSelection()
      },
      //第三：点击 — 号执行删除一行的方法
      deleteRow(index) {
        //利用数组的splice方法，将该index数据删除
        this.itemDataList.splice(index, 1);
      },
      selectionChangeHandle(val) {
        this.dataListSelections = val
      },
      selectGoods(row) {
        this.goodsSelectVisible = true
        this.$nextTick(() => {
          this.$refs.goodsSelectRef.init()
        })
      },
      async getSuppliers() {
        const res = await this.$http({
          url: `/goods/goodssupplier/getSupplies`,
          method: 'get',
          params: this.$http.adornParams()
        })
        let data = res.data
        if (data && data.code === 0) {
          this.suppliers = data.data
        }
      },
      setSuppliers() {
        for (let index in this.suppliers) {
          let item = this.suppliers[index]
          if (this.dataForm.supplierName === item.supplierName) {

            this.dataForm.supplierId = item.supplierId
            this.dataForm.contactTel = item.mobile
            this.dataForm.contactor = item.salesman

            return
          }
        }
      },
      async getUsers() {
        const res = await this.$http({
          url: `/sys/user/listUsers`,
          method: 'get',
          params: this.$http.adornParams()
        })
        let data = res.data
        if (data && data.code === 0) {
          this.users = data.data
        }
      },
      setUsers() {
        this.users.forEach((item) => {
          if (this.dataForm.makeUsername == item.username) {
            this.dataForm.makeUserId = item.userId;
          } else if (this.dataForm.auditUsername == item.username) {
            this.dataForm.auditUserId = item.userId;
          } else if (this.dataForm.acceptUsername == item.username) {
            this.dataForm.acceptUserId = item.userId;
          }
        });
      },
      async getDicts(type) {
        const res = await this.$http({
          url: '/base/basedict/getDict',
          method: 'get',
          params: this.$http.adornParams({
            'code': type
          })
        })
        let data = res.data
        if (data && data.code === 0) {
          if (type === 'PAY_METHOD') {
            this.paymentMethods = data.data
          }
        }
      },
    },
    directives: {
      // 通过自定义指令实现的表单自动获得光标的操作
      focus: {
        inserted: function(el) {
          if (el.tagName.toLocaleLowerCase() == "input") {
            el.focus()
          } else {
            if (el.getElementsByTagName("input")) {
              el.getElementsByTagName("input")[0].focus()
            }
          }
          el.focus()
        }
      },
      focusTextarea: {
        inserted: function(el) {
          if (el.tagName.toLocaleLowerCase() == "textarea") {
            el.focus()
          } else {
            if (el.getElementsByTagName("textarea")) {
              el.getElementsByTagName("textarea")[0].focus()
            }
          }
          el.focus()
        }
      }
    }
  }
</script>
<style lang="less" scoped>
  .el-dialog__body {
    padding: 5px 20px 30px 20px;
  }

  .goods-code-box {
    display: flex;
    justify-content: right;

    .goods-code-input {
      background-color: #fff;

      .el-input__inner {
        border: 0px !important;
        background-color: #fff;
      }
    }

    .chose-button {
      width: 18px;
      padding: 3px 1px;
      margin-left: 2px;
    }
  }

  .el-divider {
    margin-bottom: 5px;
  }

  .icon {
    margin-right: 0px;
  }

  .delete-button {
    padding: 3px 5px;
  }

  .el-textarea__inner {
    line-height: 1 !important;
  }
</style>
